package com.imufe.springbootshiro.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Auther: sunYong
 * @Date: 2019/2/7 22:53
 * @Description: ${package_name}
 * shiro的配置类
 */
@Configuration
public class ShiroConfig {
    /*创建ShiroFilterFactoryBean*/
    @Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//    设置安全管理
    shiroFilterFactoryBean.setSecurityManager(securityManager);

    /*添加shiro内置过滤器，实现相关权限拦截器*/
//    anon：无需认证（登录）可以访问
//    authc：必须认证才可访问
//    user：如果使用rememberMe的功能可以直接访问
//    perms：该资源必须得到资源权限才可以访问
//    role：该资源必须得到角色权限才可以访问
    Map<String,String> filterMap = new LinkedHashMap<>();
//    filterMap.put("/add","authc");
//    filterMap.put("/update","authc");
        filterMap.put("/testThymeLeaf","anon");
        filterMap.put("/toLogin","anon");

//        授权过滤器
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/update","perms[user:update]");
    filterMap.put("/*","authc");//拦截所有


//    修改跳转的登录页面
shiroFilterFactoryBean.setLoginUrl("/login");
//设置未授权提示页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
    return shiroFilterFactoryBean;
}

    /*创建DefaultWebSecurityManager*/
    @Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//    关联realm
    securityManager.setRealm(userRealm);
    return securityManager;
}
    /*创建Realm*/
    @Bean(name = "userRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }

    /*配置ShiroDialect，用于thymeleaf和shiro标签配合使用*/
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
